package mspbots.next.ticket.core.grader.interceptor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import mspbots.next.ticket.core.grader.AbstractGradeRuleAdapter;
import mspbots.next.ticket.core.grader.GradeRuleInterceptorRegistration;
import mspbots.next.ticket.core.points.PointResult;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

@Log4j2
@Service(value = "CUSTOMER_RESPONDED_POINT_RULE")
public class CustomerRespondedRuleInterceptor extends AbstractGradeRuleAdapter {

    private static final String RULE_KEY = "CustomerResponded";
    private List<CustomerRespondedParam> params;
    @Override
    public Mono<GradeRuleInterceptorRegistration> prepare(GradeRuleInterceptorRegistration gradeRuleInterceptorRegistration) {
        return Flux.just()
                .doFinally(r -> this.params = super.objectMapper
                        .convertValue(gradeRuleInterceptorRegistration.getRule().getParams(),
                                new TypeReference<>() {
                                }))
                .then(Mono.just(gradeRuleInterceptorRegistration));
    }

    @Override
    public Mono<PointResult> scoring(JsonNode ticket) {
        int point = 0;
        Boolean customerUpdatedFlag = super.getBooleanValue(ticket.get("customerUpdatedFlag"));
        if (customerUpdatedFlag != null) {
            point = params.parallelStream().filter(p -> p.isSelected() && customerUpdatedFlag)
                    .mapToInt(CustomerRespondedParam::getPoints).sum();
        }
        return Mono.just(PointResult.withDefault().point(point)
                .detail(PointResult.Detail.with(point, Map.of("customerUpdatedFlag", customerUpdatedFlag), RULE_KEY)));
    }

    @Data
    private static class CustomerRespondedParam {
        private Integer index;
        private Integer points;
        private String condition;
        private boolean selected;
    }
}
